//
//  Insurance.m
//  PhotoAnnotate
//
//  Created by Bassem El-Tamimi on 23.01.11.
//  Copyright 2011 ePapyrus GmbH. All rights reserved.
//

#import "Insurance.h"
#import "InsuredDevice.h"
#import "Reachability.h"

#define ADDRESS_TITLE_COMPANY 2
#define ADDRESS_TITLE_MR 1
#define ADDRESS_TITLE_MRS 0

#define DATE_ALERT 0
#define MISSING_DATA_ALERT 1
#define BIRTH_DATE_ALERT 2
#define NO_INTERNET_ALERT 3
#define TRANSFER_FAILED_ALERT 4
#define TRANSFER_SUCCESS_ALERT 5

#define DATE_NO 0
#define DATE_YES 1

@implementation Insurance

@synthesize conditionsAccepted;
@synthesize uninsurable;
@synthesize insured;
@synthesize purchaseDate;
@synthesize birthDate;
@synthesize notOlderThanInMonths;
@synthesize imageURL;
@synthesize address;
@synthesize bankConnection;
@synthesize robbery;
@synthesize monthlyRate;
@synthesize monthlyRateIncRobbery;
@synthesize importantInformation;
@synthesize paymentPeriod;
@synthesize propertyListData;
@synthesize insuredDevice;
@synthesize insurancePricelist;

@synthesize connection;

@synthesize _agentNumber;
@synthesize _username;
@synthesize _password;

#pragma mark -
#pragma mark Initialization and data management


- (id) init {
	
    self = [super init];
    if (self) {
        NSString *errorDesc = nil;
        NSPropertyListFormat format;
		
		NSString *plistPath = nil;
		
		// check if a saved version of InsuranceData.plist exists in Documents directory, otherwise read it from the bundle
		if (self.InsuranceDataExists) {
			NSString *sandboxPath = NSHomeDirectory();
			plistPath = [sandboxPath stringByAppendingPathComponent:@"Documents/InsuranceData.plist"];
		} else {
			plistPath = [[NSBundle mainBundle] pathForResource:@"InsuranceData" ofType:@"plist"];
		}


        NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
        NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
											  propertyListFromData:plistXML
											  mutabilityOption:NSPropertyListMutableContainersAndLeaves
											  format:&format
											  errorDescription:&errorDesc];
		
        if (!temp) {
            NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
        }
				
		self.propertyListData = [NSMutableDictionary dictionaryWithDictionary:temp];
		
		self.address = [NSMutableDictionary dictionaryWithCapacity:9];
		self.bankConnection = [NSMutableDictionary dictionaryWithCapacity:4];
		self.importantInformation = [NSMutableDictionary dictionaryWithCapacity:2];

		self.insuredDevice = [[[InsuredDevice alloc] init] autorelease];
		
		//self.insurancePricelist = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InsurancePricelist" ofType:@"plist"]];
		self.insurancePricelist = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InsurancePricelist" ofType:@"plist"]];
        
		self.uninsurable = NO;
		self.conditionsAccepted = NO;
		
		[self updateProperties];
    }
    return self;
}

// Init controller with agent number, username and password
- (id) initWithAgentNumber:(NSString* )agentNumber andUsername:(NSString *)myUsername andPassword:(NSString *)myPassword {
	
    self = [super init];
    if (self) {
        NSString *errorDesc = nil;
        NSPropertyListFormat format;
		
        self._agentNumber = agentNumber;
        self._username = myUsername;
        self._password = myPassword;
        
		NSString *plistPath = nil;
		
		// check if a saved version of InsuranceData.plist exists in Documents directory, otherwise read it from the bundle
		if (self.InsuranceDataExists) {
			NSString *sandboxPath = NSHomeDirectory();
			plistPath = [sandboxPath stringByAppendingPathComponent:@"Documents/InsuranceData.plist"];
		} else {
			plistPath = [[NSBundle mainBundle] pathForResource:@"InsuranceData" ofType:@"plist"];
		}
        
        
        NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
        NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
											  propertyListFromData:plistXML
											  mutabilityOption:NSPropertyListMutableContainersAndLeaves
											  format:&format
											  errorDescription:&errorDesc];
		
        if (!temp) {
            NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
        }
        
		self.propertyListData = [NSMutableDictionary dictionaryWithDictionary:temp];
		
		self.address = [NSMutableDictionary dictionaryWithCapacity:9];
		self.bankConnection = [NSMutableDictionary dictionaryWithCapacity:4];
		self.importantInformation = [NSMutableDictionary dictionaryWithCapacity:2];
        
		self.insuredDevice = [[[InsuredDevice alloc] init] autorelease];
		
		//self.insurancePricelist = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InsurancePricelist" ofType:@"plist"]];
		self.insurancePricelist = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InsurancePricelist" ofType:@"plist"]];
        
		self.uninsurable = NO;
		self.conditionsAccepted = NO;
		
		[self updateProperties];
    }
    return self;
}

- (void)updateProperties
{
	insured = (BOOL)[[self.propertyListData objectForKey:@"Insured"] boolValue];
	self.purchaseDate = [self.propertyListData objectForKey:@"PurchaseDate"];
	self.birthDate = [self.propertyListData objectForKey:@"BirthDate"];
	self.notOlderThanInMonths = [self.propertyListData objectForKey:@"NotOlderThan_inMonths"];
	self.imageURL = [self.propertyListData objectForKey:@"ImageURL"];
	
	NSDictionary *temp = [self.propertyListData objectForKey:@"Address"];
	[self.address setDictionary:temp];

	temp = [self.propertyListData objectForKey:@"BankConnection"];
	[self.bankConnection setDictionary:temp];
	
	robbery = (BOOL)[[self.propertyListData objectForKey:@"Robbery"] boolValue];
	
	self.paymentPeriod = [self.propertyListData objectForKey:@"PaymentPeriod"];
		
	NSString *deviceIdentifier = [NSString stringWithFormat:@"%@,%@", [self.insuredDevice machine], [self.insuredDevice machineMemory]];
	
	if ([self.insurancePricelist objectForKey:deviceIdentifier] == nil || [[self.insurancePricelist objectForKey:deviceIdentifier] floatValue] == 0.0) {
		self.uninsurable = YES;
		self.monthlyRate = [self.propertyListData objectForKey:@"MonthlyRate"];
		self.monthlyRateIncRobbery = [self.propertyListData objectForKey:@"MonthlyRateIncRobbery"];
	} else {
		self.monthlyRate = [self.insurancePricelist objectForKey:deviceIdentifier];

		if ([self.monthlyRate floatValue] > 5.0) {
			float temp = [self.monthlyRate floatValue] + [[self.insurancePricelist objectForKey:@"plusRobberyHigh"] floatValue];
			self.monthlyRateIncRobbery = [NSNumber numberWithFloat:temp];
		} else {
			float temp = [self.monthlyRate floatValue] + [[self.insurancePricelist objectForKey:@"plusRobberyLow"] floatValue];
			self.monthlyRateIncRobbery = [NSNumber numberWithFloat:temp];
		}
	}
	
	[self.importantInformation setDictionary:[self.propertyListData objectForKey:@"ImportantInformation"]];
	
	// just for testing
	// insured = YES;
	
}

- (void)updatePropertyListData
{
	[self.propertyListData setObject:[NSNumber numberWithBool:insured] forKey:@"Insured"];
	[self.propertyListData setObject:self.purchaseDate forKey:@"PurchaseDate"];
	[self.propertyListData setObject:self.birthDate forKey:@"BirthDate"];
	[self.propertyListData setObject:self.notOlderThanInMonths forKey:@"NotOlderThan_inMonths"];
	//[self.propertyListData setObject:self.imageURL forKey:@"ImageURL"];
	
	[self.propertyListData setObject:self.address forKey:@"Address"];
	[self.propertyListData setObject:self.bankConnection forKey:@"BankConnection"];
	
	[self.propertyListData setObject:[NSNumber numberWithBool:robbery] forKey:@"Robbery"];
	[self.propertyListData setObject:self.paymentPeriod forKey:@"PaymentPeriod"];

}


- (BOOL)saveChanges
{
	NSString *error;
	
	NSString *sandboxPath = NSHomeDirectory();
	NSString *plistPath = [sandboxPath stringByAppendingPathComponent:@"Documents/InsuranceData.plist"];
//	NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"InsuranceData" withExtension:@"plist"];
	
	NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:self.propertyListData
																   format:NSPropertyListXMLFormat_v1_0
														 errorDescription:&error];
	
    if(plistData) {
//        [plistData writeToURL:plistURL atomically:YES];
		[plistData writeToFile:plistPath atomically:YES];
    }
    else {
        NSLog(@"%@", error);
        [error release];
		return NO;
    }
	return YES;
}

- (BOOL)InsuranceDataExists
{
	NSString *sandboxPath = NSHomeDirectory();
	NSString *docPath = [sandboxPath stringByAppendingPathComponent:@"Documents/InsuranceData.plist"];
	return [[NSFileManager defaultManager] fileExistsAtPath:docPath];
}


#pragma mark -
#pragma mark Text formatting

- (NSString *)deviceString
{
	int day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:self.purchaseDate];
	int day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:[NSDate dateWithTimeIntervalSince1970:0]];
	
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
	[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
	[dateFormatter setLocale:[NSLocale currentLocale]];
	NSString *formattedPurchaseDate = [dateFormatter stringFromDate:self.purchaseDate];
	
	if (day1 == day2) {
		formattedPurchaseDate = @"";
	}
	
	
	[dateFormatter release];
	
	//UIDevice *aDevice = [UIDevice currentDevice];
	
	NSString *insuredDeviceString = [NSString stringWithFormat:@"%@: %@\r%@: %@\r%@: %@", 
									NSLocalizedString(@"INSURANCE_DEVICE_MODEL_LABEL", @"Model"), 
									[self.insuredDevice deviceDescription], 
									NSLocalizedString(@"INSURANCE_DEVICE_SERIAL_NO_LABEL", @"Serial No"),
									[self.insuredDevice serialNumber], 
									NSLocalizedString(@"INSURANCE_DEVICE_PURCHASE_DATE_LABEL", @"Purchase Date"), 
									formattedPurchaseDate];
	return insuredDeviceString;
	
}


- (NSString *)birthDateString
{
	int day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:self.birthDate];
	int day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:[NSDate dateWithTimeIntervalSince1970:0]];
	
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
	[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
	[dateFormatter setLocale:[NSLocale currentLocale]];
	NSString *formattedBirthDate = [dateFormatter stringFromDate:self.birthDate];
	
	if (day1 == day2) {
		formattedBirthDate = @"";
	}
	
	
	[dateFormatter release];
	
	//UIDevice *aDevice = [UIDevice currentDevice];
	
	NSString *formattedBirthDateString = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"INSURANCE_BIRTH_DATE_LABEL", @"Birthday"), formattedBirthDate];
	
	return formattedBirthDateString;
}

- (NSString *)addressString
{
	NSString *aNameString = [NSString stringWithString:@""];
	NSString *addressString = [NSString stringWithString:@""];
	
	if ([[self.address objectForKey:@"Surname"] length] > 0) {
		
		switch ([[self.address objectForKey:@"Title"] integerValue]) {
			case ADDRESS_TITLE_COMPANY:
				aNameString = [aNameString stringByAppendingFormat:@"%@", [self.address objectForKey:@"Surname"]];
				break;
			case ADDRESS_TITLE_MR:
				aNameString = [aNameString stringByAppendingFormat:@"%@ %@ %@", NSLocalizedString(@"INSURANCE_ADDRESS_TITLE_MR", @"Mr."), [self.address objectForKey:@"Name"], [self.address objectForKey:@"Surname"]];
				break;
			case ADDRESS_TITLE_MRS:
				aNameString = [aNameString stringByAppendingFormat:@"%@ %@ %@", NSLocalizedString(@"INSURANCE_ADDRESS_TITLE_MRS", @"Mrs."), [self.address objectForKey:@"Name"], [self.address objectForKey:@"Surname"]];
				break;
			default:
				break;
		}
		
		addressString = [addressString stringByAppendingFormat:@"%@\r%@\r%@ %@\r%@\r%@\r%@", 
						 aNameString, 
						 [self.address objectForKey:@"StreetAddress"], 
						 [self.address objectForKey:@"PostalCode"], 
						 [self.address objectForKey:@"City"], 
						 [self.address objectForKey:@"Country"], 
						 [self.address objectForKey:@"EMail"], 
						 [self.address objectForKey:@"PhoneNumber"]];
	} else {
		addressString = [addressString stringByAppendingFormat:@"%@", NSLocalizedString(@"INSURANCE_ADDRESS_EMPTY", @"Enter Address Here")];
	}
	
	return addressString;
}

- (NSString *)bankConnectionString
{
	NSString *aBankConnectionString = [NSString stringWithString:@""];
	if ([[self.bankConnection objectForKey:@"BankName"] length] > 0) {
		aBankConnectionString = [aBankConnectionString stringByAppendingFormat:@"%@\r%@\r%@: %@\r%@: %@", 
								 [self.bankConnection objectForKey:@"BankName"], 
								 [self.bankConnection objectForKey:@"AccountName"], 
								 NSLocalizedString(@"INSURANCE_BANK_CONNECTION_ACCOUNT", @"Account No."), [self.bankConnection objectForKey:@"AccountNumber"], 
								 NSLocalizedString(@"INSURANCE_BANK_CONNECTION_ROUTING", @"Routing No."), [self.bankConnection objectForKey:@"RoutingNumber"]];  
	} else {
		aBankConnectionString = [aBankConnectionString stringByAppendingFormat:@"%@", NSLocalizedString(@"INSURANCE_BANK_CONNECTION_EMPTY", @"Enter Bank Connection Here")];
	}
	
	return aBankConnectionString;
}

- (NSString *)monthlyRateString
{
	NSString *aMonthlyRateString = [NSString stringWithString:@""];
	float rate = 0.0;
	NSLocale *activeLocale = [NSLocale currentLocale];
	NSString *localeCode = [activeLocale localeIdentifier];
	
	if (robbery) {
		switch ([paymentPeriod intValue]) {
			case 1:
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%@ € %@", [self.monthlyRateIncRobbery stringValue],  NSLocalizedString(@"INSURANCE_MONTHLY_RATE_LABEL", @"per month")];
				break;
			case 3:
				rate = 3.0 * [self.monthlyRateIncRobbery floatValue];
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%.2f € %@", rate,  NSLocalizedString(@"INSURANCE_QUARTELY_RATE_LABEL", @"per quarter")];
				break;
			case 6:
				rate = 6.0 * [self.monthlyRateIncRobbery floatValue];
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%.2f € %@", rate,  NSLocalizedString(@"INSURANCE_BIANNUAL_RATE_LABEL", @"semiannually")];
				break;
			case 12:
				rate = 12.0 * [self.monthlyRateIncRobbery floatValue];
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%.2f € %@", rate,  NSLocalizedString(@"INSURANCE_ANNUALLY_RATE_LABEL", @"per year")];
				break;
			default:
				break;
		}
		
	} else {
		switch ([paymentPeriod intValue]) {
			case 1:
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%@ € %@", [self.monthlyRate stringValue],  NSLocalizedString(@"INSURANCE_MONTHLY_RATE_LABEL", @"per month")];
				break;
			case 3:
				rate = 3.0 * [self.monthlyRate floatValue];
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%.2f € %@", rate,  NSLocalizedString(@"INSURANCE_QUARTELY_RATE_LABEL", @"per quarter")];
				break;
			case 6:
				rate = 6.0 * [self.monthlyRate floatValue];
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%.2f € %@", rate,  NSLocalizedString(@"INSURANCE_BIANNUAL_RATE_LABEL", @"semiannually")];
				break;
			case 12:
				rate = 12.0 * [self.monthlyRate floatValue];
				aMonthlyRateString = [aMonthlyRateString stringByAppendingFormat:@"%.2f € %@", rate,  NSLocalizedString(@"INSURANCE_ANNUALLY_RATE_LABEL", @"per year")];
				break;
			default:
				break;
		}
		
	}
	return [localeCode compare:@"de_DE"] == NSOrderedSame ? [aMonthlyRateString stringByReplacingOccurrencesOfString:@"." withString:@","]: aMonthlyRateString;
}





- (NSString *)importantInformationString
{
	NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
	NSArray* languages = [defs objectForKey:@"AppleLanguages"];
	NSString* preferredLang = [languages objectAtIndex:0];

	return (NSString *)[self.importantInformation objectForKey:preferredLang];
}

- (void)toggleRobbery
{
	if (robbery) {
		robbery = NO;
	} else {
		robbery = YES;
	}
}

- (void)conditionsHaveBeenAccepted
{
	conditionsAccepted = YES;
}

- (void)conditionsHaveBeenRejected
{
	conditionsAccepted = NO;
}

#pragma mark -
#pragma mark data preparation method

- (BOOL)noDataMissing
{
	// initialize the string to hold missing data descriptions
	NSString *missingData = [NSString stringWithString:@""];
	
	// check if a valid date has been saved
	int day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:self.purchaseDate];
	int day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:[NSDate dateWithTimeIntervalSince1970:0]];
	
	if (day1 == day2) {
		// add date to missing data string
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_PURCHSE_DATE", @"Purchase Date")];
	}
	
	// check address details
	
	// check first if comapany or person was selected
	if ([[self.address objectForKey:@"Title"] integerValue] == ADDRESS_TITLE_COMPANY) {
		// company
		if ([[self.address objectForKey:@"Surname"] length] == 0) {
			missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_COMPANY", @"Company Name")];
		}
	} else {
		// person
		if ([[self.address objectForKey:@"Surname"] length] == 0) {
			missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_SURNAME", @"Surname")];

		}
		if ([[self.address objectForKey:@"Name"] length] == 0) {
			missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_FIRST_NAME", @"First Name")];

		}
	}
	
	// check street address details
	if ([[self.address objectForKey:@"StreetAddress"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_STREET_ADDRESS", @"Street Address")];

	}
	
	if ([[self.address objectForKey:@"PostalCode"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_POSTAL_CODE", @"Postal Code")];
	}

	if ([[self.address objectForKey:@"City"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_CITY", @"City")];
	}
	
	if ([[self.address objectForKey:@"Country"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_COUNTRY", @"Country")];
	}
		
	
	// check for other contact details
	if ([[self.address objectForKey:@"EMail"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_EMAIL", @"E-Mail")];
	}
	
	if ([[self.address objectForKey:@"PhoneNumber"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_PHONE_NUMBER", @"Phone Number")];
	}
	
	// check if a valid date has been saved for birth date
	int day3 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:self.birthDate];
	int day4 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:[NSDate dateWithTimeIntervalSince1970:0]];
	
	if (day3 == day4) {
		// add date to missing data string
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_BIRTH_DATE", @"Birthday")];
	}
	
	
	// check bank details
	if ([[self.bankConnection objectForKey:@"RoutingNumber"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_BANK_ROUTING_NUMBER", @"Bank Routing Number")];
	}
	
	if ([[self.bankConnection objectForKey:@"BankName"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_BANK_NAME", @"Bank Name")];
	}
	
	if ([[self.bankConnection objectForKey:@"AccountNumber"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_BANK_ACCOUNT_NUMBER", @"Account Number")];
	}	
	
	if ([[self.bankConnection objectForKey:@"AccountName"] length] == 0) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_BANK_ACCOUNT_NAME", @"Account Name")];
	}
	
	if (!conditionsAccepted) {
		missingData = [missingData stringByAppendingFormat:@"%@\r", NSLocalizedString(@"INSURANCE_MISSING_DATA_CONITIONS_ACCEPTANCE", @"You have not accepted the insurance conditions")];
	}
	
	NSString *missingDataString = [NSString stringWithFormat:@"%@\r%@%@", NSLocalizedString(@"INSURANCE_MISSING_DATA_ALERT_HEADER_TEXT", @"The following data is missing:"), 
								   missingData, 
								   NSLocalizedString(@"INSURANCE_MISSING_DATA_ALERT_FOOTER_TEXT", @"Please enter this information before asking for an insurance.")];
	
	
	if ([missingData length] > 0){
		// show an alert detailing the missing data
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"INSURANCE_MISSING_DATA_ALERT_TITLE", @"Data Missing") 
														message:missingDataString 
													   delegate:self 
											  cancelButtonTitle:NSLocalizedString(@"INSURANCE_MISSING_DATA_ALERT_OK_BUTTON_TITLE", @"OK") 
											  otherButtonTitles:nil];
		alert.tag = MISSING_DATA_ALERT;
		[alert show];	
		[alert release];
		
	}
	
	return ([missingData length] == 0)?YES:NO;
		
}

- (NSString *)xmlDataString
{
	NSString *xmlDataTemplatePath = [[NSBundle mainBundle] pathForResource:@"EWP_XML_Template" ofType:@"txt"];
	NSString *xmlDataTemplate = [NSString stringWithContentsOfFile:xmlDataTemplatePath encoding:NSUTF8StringEncoding error:NULL];
	
	NSString *xmlData = [xmlDataTemplate stringByReplacingOccurrencesOfString:@"__Strasse__" withString:[self.address objectForKey:@"StreetAddress"]];
	
	switch ([[self.address objectForKey:@"Title"] integerValue]) {
		case ADDRESS_TITLE_COMPANY:
			xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Anrede__" withString:@"Firma"];
			break;
		case ADDRESS_TITLE_MR:
			xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Anrede__" withString:@"Herr"];
			break;
		case ADDRESS_TITLE_MRS:
			xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Anrede__" withString:@"Frau"];
			break;
		default:
			break;
	}
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Vorname__" withString:[self.address objectForKey:@"Name"]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Nachname__" withString:[self.address objectForKey:@"Surname"]];

	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Plz__" withString:[self.address objectForKey:@"PostalCode"]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Ort__" withString:[self.address objectForKey:@"City"]];
	
	if ([[self.bankConnection objectForKey:@"RoutingNumber"] length] == 8) {
		// we are in Germany
		xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Laenderkennzeichen__" withString:@"DE"];
	} else {
		// we are in Austria
		xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Laenderkennzeichen__" withString:@"AT"];
	}
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__EMail__" withString:[self.address objectForKey:@"EMail"]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Festnetz1__" withString:[self.address objectForKey:@"PhoneNumber"]];

	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Kontoinhaber__" withString:[self.bankConnection objectForKey:@"AccountName"]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Bank__" withString:[self.bankConnection objectForKey:@"BankName"]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Blz__" withString:[self.bankConnection objectForKey:@"RoutingNumber"]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Kontonummer__" withString:[self.bankConnection objectForKey:@"AccountNumber"]];

	
		
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Typ__" withString:[self.insuredDevice deviceDescription]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Nummer__" withString:[self.insuredDevice serialNumber]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Zahlungsweise__" withString:[self.paymentPeriod stringValue]];
	
	NSString *aDevice = [[UIDevice currentDevice] model];
	
	if ([aDevice compare:@"iPhone"] == NSOrderedSame) {
		xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Geraetekennzeichen__" withString:@"73"];
		xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Sondergeraet__" withString:@""];
	} else if ([aDevice compare:@"iPod touch"] == NSOrderedSame) {
		xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Geraetekennzeichen__" withString:@"49"];
		xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Sondergeraet__" withString:@"4900228"];
	}
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Satznummer__" withString:[self.insuredDevice serialNumber]];


	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
	[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
	[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"DE"] autorelease]];
	NSString *formattedPurchaseDate = [dateFormatter stringFromDate:self.purchaseDate];
	NSString *formattedBirthDate = [dateFormatter stringFromDate:self.birthDate];
	NSString *formattedTodayDate = [dateFormatter stringFromDate:[NSDate date]];

	[dateFormatter release];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Kaufdatum__" withString:formattedPurchaseDate];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Geburtsdatum__" withString:formattedBirthDate];
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Antragsdatum__" withString:formattedTodayDate];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Exportdatum__" withString:formattedTodayDate];

	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Diebstahlschutz__" withString:robbery ? @"1" : @"0"];
	
	NSCalendar *gregorian = [[NSCalendar alloc]  initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *dateComponents = [gregorian components:NSYearCalendarUnit fromDate:self.purchaseDate];
	NSInteger year = [dateComponents year];
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Baujahr__" withString:[NSString stringWithFormat:@"%d", year]];
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Inkassoart__" withString:@"Einzug"];
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Kaufpreis__" withString:[self.insuredDevice devicePrice]];
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"__Vermittlernummer__" withString:self._agentNumber];
    
	[gregorian release];

	
//	NSLog(@"%@", xmlData);

	
	return xmlData;
								 
}


#pragma mark -
#pragma mark data transfer method

- (void)sendInsuranceDataWithinView:(UIView *)view
{
	// check if Internet is reachable
	
	if (self.internetReachable) {
		// send the data
		NSString *xmlString = [self xmlDataString];
		NSString *encodedString = [xmlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
		NSString *encodedRFCString = encodedString?[self urlencode:encodedString]:[NSString stringWithString:@""];
		
		// set @"&test=1" when testing
		
		//NSString *postString = [NSString stringWithFormat:@"%@%@%@", [NSString stringWithFormat:@"bn=%@&pw=%@&xmldata=", self._username, self._password], encodedRFCString, @"&test=0"];
        NSString *postString = [NSString stringWithFormat:@"bn=%@&pw=%@&xmldata=%@&test=%@", self._username, self._password, encodedRFCString, @"0"];
        
		NSData *postBody = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
		
		
//		NSLog(@"encodedRFCString:\r%@", encodedRFCString);
		
		NSURL *url = [NSURL URLWithString:@"https://ssl.wertgarantie.de/cgi/e/e/epapyrus/antrag.pl"];
		
		
		NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
		
		[request setHTTPMethod:@"POST"];
		
		[request setValue:[NSString stringWithFormat:@"%d", [postBody length]] forHTTPHeaderField:@"Content-Length"];
		
		[request setHTTPBody:postBody];
				
		if (encodedRFCString) {
			self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
		}
		
		HUD = [[MBProgressHUD showHUDAddedTo:view animated:YES] retain];
		
	} else {
		// alert the user
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"NO_INTERNET_ALERT_TITLE", @"No Internet") 
														message:NSLocalizedString(@"NO_INTERNET_ALERT_MESSAGE", @"Failed to connect to the Internet. Please check your network settings and retry.") 
													   delegate:self 
											  cancelButtonTitle:NSLocalizedString(@"NO_INTERNET_ALERT_OK", @"OK") 
											  otherButtonTitles: nil];
		alert.tag = NO_INTERNET_ALERT;
		[alert show];	
		[alert release];
	}

}


//simple API that encodes reserved characters according to:
//RFC 2732
//http://www.ietf.org/rfc/rfc2732.txt
- (NSString *)urlencode:(NSString *) url
{
	NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" , @"@" , @"&" , @"=" , @"+" , @"$" , @"," , @"[" , @"]", @"%E2%80%A8", nil];
	NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F" , @"%3F" , @"%3A" , @"%40" , @"%26" , @"%3D" , @"%2B" , @"%24" , @"%2C" , @"%5B" , @"%5D", @"%0A", nil];
	
	int len = [escapeChars count];
	
	NSMutableString *temp = [url mutableCopy];
	
	int i;
	for(i = 0; i < len; i++)
	{
		
		[temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i]
							  withString:[replaceChars objectAtIndex:i]
								 options:NSLiteralSearch
								   range:NSMakeRange(0, [temp length])];
	}
	
	NSString *out = [NSString stringWithString: temp];
	[temp release];
	
	return out;
}


- (BOOL)internetReachable
{
	if([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable || [[Reachability reachabilityWithHostName: @"ssl.wertgarantie.de"] currentReachabilityStatus] == NotReachable)
	{
		return NO;
	} else {
		return YES;
	}
}

#pragma mark -
#pragma mark NSConnection delegate methods


- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
{
	return request;
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
	return NO;
}

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
	
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	expectedLength = [response expectedContentLength];
	currentLength = 0;
	HUD.mode = MBProgressHUDModeDeterminate;

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	
	[HUD hide:YES];
	
//	NSLog(@"didFailWithError: %@", error);
	
	// inform the user that the upload failed
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"INSURANCE_DATA_TRANSFER_FAILED_ALERT_TITLE", @"Transfer Failed") 
													message:NSLocalizedString(@"INSURANCE_DATA_TRANSFER_FAILED_ALERT_MESSAGE", @"Transfer of your data has failed. Please retry later.") 
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"INSURANCE_DATA_TRANSFER_FAILED_ALERT_OK_BUTTON_TITLE", @"OK") 
										  otherButtonTitles: nil];
	alert.tag = TRANSFER_FAILED_ALERT;
	[alert show];	
	[alert release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//	HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
//    HUD.mode = MBProgressHUDModeCustomView;
//	[HUD hide:YES afterDelay:2];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	
	[HUD hide:YES];

	NSString *newStr = [[NSString alloc] initWithData:data
											 encoding:NSUTF8StringEncoding];
	
	NSString *firstCharacter = [newStr substringToIndex:1];
	NSString *zeroCharacter = [NSString stringWithString:@"0"];
	
	NSString *okString = [NSString stringWithString:@"ok"];
	
//	NSLog(@"firstCharacter: %@", firstCharacter);
	NSLog(@"connection data: %@", newStr);
	
	if ([firstCharacter compare:zeroCharacter] == NSOrderedSame && [newStr rangeOfString:okString].location == NSNotFound) {
		// inform the user of failure
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"INSURANCE_DATA_TRANSFER_FAILED_ALERT_TITLE", @"Transfer Failed") 
														message:NSLocalizedString(@"INSURANCE_DATA_TRANSFER_FAILED_ALERT_MESSAGE", @"Transfer of your data has failed. Please retry later.") 
													   delegate:self 
											  cancelButtonTitle:NSLocalizedString(@"INSURANCE_DATA_TRANSFER_FAILED_ALERT_OK_BUTTON_TITLE", @"OK") 
											  otherButtonTitles: nil];
		alert.tag = TRANSFER_FAILED_ALERT;
		[alert show];	
		[alert release];

	} else {
	
		// infomr the user of success
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"INSURANCE_DATA_TRANSFERED_ALERT_TITLE", @"Transfer Succeeded") 
														message:NSLocalizedString(@"INSURANCE_DATA_TRANSFERED_ALERT_MESSAGE", @"Your data has been successfully transfered. You will receive a confirmation e-mail soon.") 
													   delegate:self 
											  cancelButtonTitle:NSLocalizedString(@"INSURANCE_DATA_TRANSFERED_ALERT_OK_BUTTON_TITLE", @"OK") 
											  otherButtonTitles: nil];
		alert.tag = TRANSFER_SUCCESS_ALERT;
		[alert show];	
		[alert release];
		
		// set insured = YES;
		insured = YES;
	}
	
//	NSLog(@"Data:\r%@", newStr);
	[self updatePropertyListData];
	[self saveChanges];
	
	[newStr release];
}


#pragma mark -
#pragma mark Alert View delegate method

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	switch (alertView.tag) {
		case DATE_ALERT:
			switch (buttonIndex) {
				case DATE_NO:
					// reset to dummy date
					self.purchaseDate = [NSDate dateWithTimeIntervalSince1970:0];
					[self saveChanges];
//					NSLog(@"Reset Date to %@", [NSDate dateWithTimeIntervalSince1970:0]);
					[[NSNotificationCenter defaultCenter] postNotificationName:@"PurchaseDateChanged" object:self];
					
					break;
				case DATE_YES:
					// todays date was already saved, so nothing else needs to be done
//					NSLog(@"Date was saved");

					break;
				default:
					break;
			}
			break;
		case BIRTH_DATE_ALERT:
			switch (buttonIndex) {
				case DATE_NO:
					// reset to dummy date
					self.birthDate = [NSDate dateWithTimeIntervalSince1970:0];
					[self saveChanges];
//					NSLog(@"Reset Date to %@", [NSDate dateWithTimeIntervalSince1970:0]);
					[[NSNotificationCenter defaultCenter] postNotificationName:@"BirthDateChanged" object:self];
					
					break;
				case DATE_YES:
					// todays date was already saved, so nothing else needs to be done
//					NSLog(@"Date was saved");
					
					break;
				default:
					break;
			}
			break;
		case MISSING_DATA_ALERT:
			// nothing to do
			break;
		case NO_INTERNET_ALERT:
			// nothing to do
			break;
		case TRANSFER_FAILED_ALERT:
			// nothing to do
			break;
		case TRANSFER_SUCCESS_ALERT:
			// nothing to do
			break;
		default:
			break;
	}
	
}


#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
	HUD = nil;
}

- (void)dealloc {
    [_agentNumber release];
    [_username release];
    [_password release];
    [super dealloc];
}

@end
